<template>
  <view>
    <van-cell-group>
      <!-- 代办名称 -->
      <van-field
        label="代办名称"
        :value="todo.t_title"
        placeholder="请输入"
        :border="true"
        clearable
        required
        auto-focus
        @change="titleChange"
      />
      <!-- 代办描述 -->
      <van-field
        label="描述"
        :value="todo.t_desc"
        placeholder="请输入"
        :border="true"
        autosize
        clearable
        :maxlength="45"
        @change="descChange"
      />

      <van-collapse
        :value="collapseActiveName"
        @change="collapseChange"
        accordion
      >
        <!-- 开始时间 -->
        <van-collapse-item title="开始时间" name="开始时间" :value="startTime">
          <van-datetime-picker
            type="datetime"
            title="选择时间"
            :value="todo.t_time"
            :visible-item-count="5"
            cancel-button-text="当前日期"
            @cancel="backToToday"
            @confirm="confirmDate"
            @input="dateInput"
          />
        </van-collapse-item>
        <!-- 选择看板 -->
        <van-collapse-item
          title="选择看板"
          name="选择看板"
          :value="todo.t_board.board_title"
        >
          <van-picker
            :columns="boardColumns"
            :default-index="selectBoardIndex"
            :visible-item-count="4"
            @change="boardChange"
          />
        </van-collapse-item>
        <!-- 设置优先级 -->
        <van-collapse-item
          title="设置优先级"
          name="设置优先级"
          :value="urgentList[todo.urgent - 1]"
        >
          <van-row gutter="20">
            <van-col span="8">
              <div
                :class="
                  ' tag ' + (todo.urgent == 1 ? 'normalActive' : 'normal')
                "
                @click="urgentChange(1)"
              >
                一般
              </div>
            </van-col>
            <van-col span="8">
              <div
                :class="
                  ' tag ' + (todo.urgent == 2 ? 'middleActive' : 'middle')
                "
                @click="urgentChange(2)"
              >
                中等
              </div>
            </van-col>
            <van-col span="8">
              <div
                :class="' tag ' + (todo.urgent == 3 ? 'highActive' : 'high')"
                @click="urgentChange(3)"
              >
                较高
              </div>
            </van-col>
          </van-row>
        </van-collapse-item>
      </van-collapse>

      <!-- 是否添加到手机日程 -->
      <van-cell title=" ">
        <van-checkbox
          :value="addToCalendar"
          @change="addToCalendarChange"
          icon-size="14px"
        >
          添加到手机日程表
        </van-checkbox>
      </van-cell>
    </van-cell-group>
    <van-row>
      <van-col span="6" offset="9">
        <button
          style="margin-top: 30px"
          type="default"
          @click="clickSubmitTodo"
        >
          {{ state == 1 ? ' 提交' : '修改' }}
        </button>
      </van-col>
    </van-row>
  </view>
</template>

<script>
// import moment from '@/static/todo/moment.js';

export default {
  props: ['todoFromParent', 'state'],
  components: {},
  data() {
    return {
      activePage: 0,
      todo: {
        t_title: null,
        t_desc: null,
        t_time: new Date().getTime(),
        t_board: {},
        urgent: null,
      },
      addToCalendar: false,
      collapseActiveName: '',
      urgentList: ['一般', '中等', '较难'],
      boardList: [],
      boardColumns: [],
      selectBoardIndex: 0,
    };
  },
  computed: {
    startTime() {
      // return moment(new Date(this.todo.t_time)).format('YYYY-MM-DD HH:mm');
      return this.formatDate("YYYY-mm-dd HH:MM", new Date(this.todo.t_time));
    },
  },
  methods: {
    addToCalendarChange(e) {
      this.addToCalendar = e.detail;
    },
    titleChange(e) {
      this.todo.t_title = e.detail;
    },
    descChange(e) {
      this.todo.t_desc = e.detail;
    },
    boardChange(e) {
      const { index } = e.detail;
      this.todo.t_board = this.boardList[index];
      console.log(this.todo);
    },
    collapseChange(event) {
      this.collapseActiveName = event.detail;
    },
    backToToday() {
      this.todo.t_time = new Date().getTime();
    },
    confirmDate() {
      this.collapseActiveName = '';
      console.log(this.todo);
    },
    dateInput(e) {
      console.log(e);
      this.todo.t_time = new Date(e.detail).getTime();
    },
    urgentChange(urgent) {
      this.todo.urgent = urgent;
    },
    // 添加或修改todo
    async clickSubmitTodo() {
      console.log(this.todo);
      wx.showToast({
        title: `上传中...`,
        icon: 'loading',
      });
      var address = this.state == 1 ? 'addTodo' : 'changeTodoInfo';
      const res = await this.hjRequest.run(address, this.todo);
      wx.hideToast();
      wx.showToast({
        title: `上传成功`,
        duration: 800,
      });
      console.log(res);
      if (this.addToCalendar) {
        console.log('添加到日程表');
        wx.addPhoneCalendar({
          title: this.todo.t_title,
          startTime: this.todo.t_time / 1000,
          description: this.todo.t_desc == null ? '' : this.todo.t_desc,
        }).then((res) => {
          console.log(res);
        });
      }
      this.$emit('addFinish');
    },
    async getBoard() {
      const res = await this.hjRequest.run('findBoard');
      console.log(res);
      this.boardList = [];
      this.boardColumns = [];
      res.boardList.forEach((item) => {
        this.boardList.push({
          board_title: item.b_title,
          board_id: item._id,
        });
        this.boardColumns.push(item.b_title);
      });
    },
    formatDate(fmt,date) { 
      let ret;
      const opt = {
          "Y+": date.getFullYear().toString(),        // 年
          "m+": (date.getMonth() + 1).toString(),     // 月
          "d+": date.getDate().toString(),            // 日
          "H+": date.getHours().toString(),           // 时
          "M+": date.getMinutes().toString(),         // 分
          "S+": date.getSeconds().toString()          // 秒
          // 有其他格式化字符需求可以继续添加，必须转化成字符串
      };
      for (let k in opt) {
          ret = new RegExp("(" + k + ")").exec(fmt);
          if (ret) {
              fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
          };
      };
      return fmt;
}        
  },
  async created() {
    await this.getBoard();
    this.todo = JSON.parse(JSON.stringify(this.todoFromParent));
    if (this.state == 1) {
      // 添加代办时候默认选中第一个
      this.todo.t_board = this.boardList[0];
      this.todo.t_board.board_index = 0;
    } else if (this.state == 2) {
      // 从看板页查看详情
      this.selectBoardIndex = this.todo.t_board.board_index;
    } else if (this.state == 3) {
      // 从日期页查看详情,需要根据board列表获取选中看板下标
      this.boardList.forEach((item, index) => {
        if (item.board_id == this.todo.t_board.board_id) {
          this.selectBoardIndex = index;
          this.todo.t_board.board_index = index;
        }
      });
    }
    this.todo.t_time = new Date(this.todo.t_time).getTime();
    console.log(this.selectBoardIndex);
    console.log('todo');
    console.log(this.todo);
  },
};
</script>
<style scoped>
.tag {
  width: 100%;
  height: 30px;
  display: inline-block;
  text-align: center;
  line-height: 30px;
  border-radius: 5px;
  color: rgb(31, 30, 30);
}
.normal {
  background-color: rgb(246, 244, 245);
}
.normalActive {
  background-color: rgb(139, 139, 139);
}
.middle {
  background-color: rgb(245, 242, 235);
}
.middleActive {
  background-color: rgb(245, 154, 81);
}
.high {
  background-color: rgb(249, 233, 233);
}
.highActive {
  background-color: rgb(238, 101, 91);
}
</style>
